package org.springboot;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

import java.util.Map;

public class GuoSpringApplication {
    public static void run(Class clazz) {
        //创建Spring容器 (需要有userController这个Bean)
        AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        applicationContext.register(clazz); //注册bean
        //刷新容器 请求userController中的test路径,
        // 会去容器里面寻找Controller相关的Bean,
        // 找到了就通过反射将结果返回
        applicationContext.refresh();

        // 有tomcat 就启动Tomcat 有jetty就启动jetty
        WebServer webServer = getWebServer(applicationContext);
        webServer.start(applicationContext);
    }

    private static WebServer getWebServer(WebApplicationContext applicationContext) {
        //tomcat jetty
        //key为beanName,value为Bean对象
        Map<String, WebServer> webServers = applicationContext.getBeansOfType(WebServer.class);
        if (webServers.isEmpty()) {
            throw new NullPointerException();
        }
        if (webServers.size() > 1) {
            throw new IllegalStateException();
        }
        //返回唯一的一个
        return webServers.values().stream().findFirst().get();
    }
}
